<?php

namespace App\Http\Middleware;

use App\Http\Controllers\JwtController;
use App\Models\AppInviteCode;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

/**
 * 验证前台邀请码访问
 */
class CheckAppInviteCode
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        return $next($request); //验证通过   正式删除

        $appInviteCodeModel = new AppInviteCode();
        $isExistsInviteCode = $appInviteCodeModel->isExistsInviteCode();
        //没有一个邀请码，就直接放行
        if (empty($isExistsInviteCode)) {
            $request->invite_code_id = null; //邀请码id
            return $next($request); //验证通过   正式删除
        }

        $invite_code = $this->getInviteCode($request);

        if ($invite_code == 'cdbottle123') {
            return $next($request); //验证通过  测试时 绕过验证
        }
        if (empty($invite_code) || strlen($invite_code) != 6 || !is_numeric($invite_code)) {
            Log::error('邀请码错误，请重新输入1-' . $invite_code);
            return  response()->json(['code' => 302, 'msg' => '邀请码错误，请重新输入']);
        }

        //验证token有效期
        try {
            $invite_code_id = $appInviteCodeModel->checkInviteCode($invite_code);
            if (is_string($invite_code_id)) {
                Log::error('邀请码错误，请重新输入2-' . $invite_code);
                return  response()->json(['code' => 302, 'msg' => $invite_code_id]);
            }
        } catch (\Exception $e) {
            Log::error('邀请码错误，请重新输入3-' . $invite_code);
            return  response()->json(['code' => 302, 'msg' => '邀请码错误，请重新输入']); //异常也失败
        }
        $request->invite_code_id = $invite_code_id; //邀请码id
        return $next($request); //验证通过
    }

    /**
     * 获取请求参数中的 app_invite_code
     * @param request  object 请求参数对象
     */
    public function getInviteCode($request)
    {
        $invite_code = $request->app_invite_code;

        return $invite_code;
    }
}
